package com.jeestudio.utils;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by shuttle on 18/11/19.
 */
public class IPUtils {
    /**
     * 获取远程机器ip地址
     *
     * @param request
     * @return
     */
    public static String getRemoteIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
            //多次反向代理后会有多个ip值，第一个ip才是真实ip
            int index = ip.indexOf(",");
            if (index != -1) {
                return ip.substring(0, index);
            } else {
                return ip;
            }
        }
        ip = request.getHeader("X-Real-IP");
        if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
            return ip;
        }

        return request.getRemoteAddr();
    }

    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getParameter("ip");
        //LOGGER.info("getIpAddress1,ip=" + ip);
        if(StringUtils.isBlank(ip) || ip.startsWith("172.") || ip.startsWith("192.168") || ip.startsWith("10.")){
            ip = getRemoteIp(request);
            //LOGGER.info("getIpAddress2,ip=" + ip);
        }
        if(StringUtils.isBlank(ip) || ip.startsWith("172.") || ip.startsWith("192.168") || ip.startsWith("10.")){
            ip = request.getHeader("x-forwarded-for");
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_CLIENT_IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_X_FORWARDED_FOR");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
            }
        }
        //LOGGER.info("getIpAddress3,ip=" + ip);
        int index = ip.indexOf(",");
        if (index != -1) {
            ip = ip.substring(0, index);
        }
        // LOGGER.info("getIpAddress4,ip=" + ip);
        return ip;
    }
}
